package com.atguigu.b;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author 快点干早点散
 * @Create 2025/3/20 21:24
 * Description:
 */
public class ReflectionDemo {


    public static void main(String[] args) throws Exception {
        //accessField();

       // accessSetField();

        accessMethod();
        // invokeMethod();
    }

    private static void accessMethod() throws NoSuchMethodException, NoSuchFieldException {
       Class sdt= Student.class;
        System.out.println(sdt.getMethod("getScore", String.class));
        System.out.println(sdt.getMethod("getName"));
        System.out.println(sdt.getDeclaredMethod("getGrade", int.class));
    }

    private static void accessField() throws NoSuchFieldException {
        Class sdt = Student.class;
        Field[] fields = sdt.getFields();
        for (Field field : fields) {
            System.out.println("field = " + field);
        }
        System.out.println(sdt.getDeclaredField("grade"));
    }


    private static void accessSetField() throws Exception {
        Dog dog = new Dog("哈士奇");
        System.out.println(dog.getDogName()); // "哈士奇"

        Class c=dog.getClass();
        Field declaredField = c.getDeclaredField("dogName");
         declaredField.setAccessible(true);
         declaredField.set(dog,"泰迪");
        System.out.println(dog.getDogName());

    }

    public static void invokeMethod() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String s0 = "hello word";
        String r1 = s0.substring(6);

        String s = "hello word";
        Method m = s.getClass().getMethod("substring", int.class);
        String r = (String) m.invoke(s, 6);
        System.out.println("r = " + r);
    }
}

class Person {
    public String name;

    public String getName() {
        return "Person";
    }
}

class Student extends Person {
    public int score;
    private int grade;

    public int getScore(String type) {
        return 99;
    }

    private int getGrade(int year) {
        return 1;
    }
}

class Dog {
    private String dogName;

    public Dog(String dogName) {
        this.dogName = dogName;
    }

    public String getDogName() {
        return this.dogName;
    }
}
